﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Services.Protocols;
using Data;
using Data.LINQ;
using D = Dimok;
using ADs = Dimok.Data.ADs;
using Dimok.Exceptions;
using Dimok.Web.UI;

namespace WSU {
	[WebService(Namespace = "http://motobankcorp/manager/Admin/Users")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	[ScriptService]
	public class Users : System.Web.Services.WebService {
		Data.LINQ.MotoBank db;
		public Users() {
			db = new Data.LINQ.MotoBank();
		}

		[WebMethod]
		public void Collection_SyncBuckets(Dictionary<string,string[]>LoginsPerBucket ) {
			try {
				foreach (var groupName in LoginsPerBucket.Keys) {
					var usersNew =
						from u in LoginsPerBucket[groupName]
						where (u + "") != "" && !db.v_ADS_Collectors.Where(c => c.GroupName == groupName).Select(c => c.sAMAccountName).Contains(u)
						select u;
					var usersRem =
						from u in db.v_ADS_Collectors.Where(c => c.GroupName == groupName).Select(c => c.sAMAccountName)
						where (u + "") != "" && !LoginsPerBucket[groupName].Contains(u)
						select u;
					var group = ADs.LDAP.FindGroup(Dimok.Config.ADS.AppGroupsDN, groupName, "cn", System.DirectoryServices.SearchScope.Subtree);
					if (group == null) throw new Exception("Group " + groupName + " can not be found in " + Dimok.Config.ADS.AppGroupsDN);
					var groupRow = ADs.LDAP.FindGroupsDS(group.Parent, ADs.Props.CN(group), false).t_Group[0];
					foreach (var u in usersRem) {
						ADs.LDAP.RemoveMemberFromGroup(u, group);
						db.t_ADS_Login_Groups.DeleteOnSubmit(db.t_ADS_Login_Groups.Single(lg => lg.SID_Group == groupRow.sid && lg.sAM_Login == u));
					}
					foreach (var u in usersNew) {
						ADs.LDAP.AddMemberToGroup(ADs.LDAP.GetUser(u, ""), ADs.Props.DN(group), false);
						db.t_ADS_Login_Groups.InsertOnSubmit(
							new Data.LINQ.t_ADS_Login_Group() { sAM_Login = u, SID_Group = groupRow.sid, DomainContext=ADs.LDAP.domainContext });
					}
					db.SubmitChanges(ConflictMode.FailOnFirstConflict);
				}
			} catch (Exception exc) {
				ASPException.Publish(exc);
				throw new Exception(ASPException.GetMessages(exc));
			}
			return;
			foreach (var groupName in LoginsPerBucket.Keys) {
				var group = ADs.LDAP.FindGroup(Dimok.Config.ADS.AppGroupsDN, groupName,"cn", System.DirectoryServices.SearchScope.Subtree);
				var users = ADs.LDAP.GetGroupUsers(group).Select(de=>ADs.Props.sAM(de).ToLower());
				var newLogins = from u in LoginsPerBucket[groupName]
												where u!= null && !users.Contains(u.ToLower())
												select u;
			}
		}

	}
}